package com.daohang361.imqq.hotLoader;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

/** 
 * @author naner E-mail:likun3344@163.com 
 * @create time：2011-5-13 下午08:43:35 
 */
public class ClassLoaderAdvisor extends ClassLoader {   
    public ClassLoaderAdvisor() {   
    }   
  
    public ClassLoaderAdvisor(ClassLoader parentLoader) {   
        super(parentLoader);   
    }   
  
    /**  
     * 加载某个类  
     * @param c  
     * @return  
     */  
   // @SuppressWarnings( { "unchecked" })   
    public Class loadClass(String className) {   
    	String tempName=className.replace(".", "/")+".class";
		//System.out.println("tempName:"+tempName);
    	//System.out.println("className:"+className);
    	 Class cNew =null;   
        byte[] bs=null;
		try {
			
			
			try {
				cNew = Class.forName(className);
				System.out.println("调用系统加载" + className + "成功!");
			} catch (Exception e) {
				System.out.println("非系统类,尝试本地加载pugin!");
			}
			if(cNew==null)
				{
				bs = loadByteCode(className,tempName);
				cNew= super.defineClass(className, bs, 0, bs.length);
				 Class.forName(className, true, this);
				}
		
		} catch (Exception e) {
			e.printStackTrace();
		}   
		
       
        return cNew;   
    }   
  
	/**  
     * 加载某个类的字节码  
     * @param c  
     * @return  
     * @throws IOException  
     */  
    private byte[] loadByteCode(String className,String tempName) throws IOException {   
        int iRead = 0;   
        String path=ClassManager.BathUrl.replace("file:", "")+tempName;
        System.out.println("从pugin目录加载path:"+path);
        FileInputStream in = null;   
        ByteArrayOutputStream buffer = null;   
        try {   
            in = new FileInputStream(path);   
            buffer = new ByteArrayOutputStream();   
            while ((iRead = in.read()) != -1) {   
                buffer.write(iRead);   
            }   
            System.out.println("加载插件class"+className+"成功");
            return buffer.toByteArray();   
        }catch (Exception e) {
			System.out.println("加载失败");
		} finally {   
            if(in!=null){
            	in.close(); 
            	buffer.close(); 
            }
             
        }
		return null;   
    }   
}  
